package main

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql" // 需要用到mysql包里的init
)

func main() {
	//"账号:密码@/数据库名?charset=字符集&parseTime=True&loc=IP地址"
	db, err := gorm.Open("mysql", "root:root@/test?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		println("连接失败")
	} else {
		println("连接成功")
	}

	defer db.Close()
	//设置全局表名禁用复数
	db.SingularTable(true)

	type Product struct {
		Id    int
		Name  string
		Price int
		Store int
	}

	// 查询数据
	product := make([]Product, 10)
	db.Find(&product)

	for _, p := range product {
		println("id: ", p.Id, "name: ", p.Name, "price: ", p.Price, "store: ", p.Store)
	}

	// 更新数据
	update := Product{Id: 1, Name: "红米"}
	db.Save(&update)

	db.Model(&Product{}).Where("id = ?", "2").Update("store", "22")

	// 新增数据
	p1 := Product{
		Id:    10,
		Name:  "大米",
		Price: 12,
		Store: 5,
	}
	db.Create(&p1)

	// 删除数据
	db.Where("id = ?", 3).Delete(&Product{})

}
